package com.hongpeiming.picupload.controller;

import com.alibaba.fastjson.JSON;
import com.hongpeiming.picupload.mapper.UserMapper;
import com.hongpeiming.picupload.pojo.JsonResult;
import com.hongpeiming.picupload.pojo.User;
import com.hongpeiming.picupload.utils.Md5CaculateUtil;
import com.hongpeiming.picupload.utils.RandomString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;

@Controller
public class testController {

    @Value("${uploadPicPath}")
    private String uploadPicPath;

    @Value("${RandomStringNumber}")
    private Integer RandomStringNumber;

    @Autowired
    private UserMapper userMapper;

    private JsonResult res;

    @RequestMapping("/test")
    public String test(Model model)
    {
        model.addAttribute("name","上传");
        return "test";
    }


    @RequestMapping("/test/upload")
    @ResponseBody
    public String testupload(HttpSession session, HttpServletRequest request) throws IOException
    {
        //开始上传时间
        long startTime = System.currentTimeMillis();

        //上传地址
        String appPath = uploadPicPath;//session.getServletContext().getRealPath(filePath);

        //根据年月日存放图片
        Calendar data = Calendar.getInstance();
        String TimePath = "\\"+data.get(Calendar.YEAR)+"\\"+data.get(Calendar.MONTH)+"\\"+data.get(Calendar.DATE);
        appPath = appPath + TimePath;

        File appRootDir = new File(appPath);
        if (!appRootDir.exists()) {
            System.out.println("存储app的文件夹不存在 appPath= " + appPath);
            //创建这个路径的文件夹
            appRootDir.mkdirs();
        } else {
            System.out.println("存储app的文件夹存在 appPath= " + appPath);
        }


        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        //判断 request 是否有文件上传
        if (multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            //获取多个上传文件name
            Iterator<String> names = multiRequest.getFileNames();


            while (names.hasNext()) {
                MultipartFile file = multiRequest.getFile(names.next().toString());


                if (file != null) {
                    String OriginalFilename = file.getOriginalFilename();

                    String FilenameArray[] = OriginalFilename.split("\\.");
                    String prefix = FilenameArray[0];
                    String suffix = FilenameArray[1];

                    String RandomPrefix;

                    for (;;)
                    {
                        RandomPrefix = RandomString.getRandomString(RandomStringNumber);
                        String FinalName = RandomPrefix+"."+suffix;
                        File FinalFile = new File(FinalName);
                        if (!FinalFile.exists())
                        {
                            System.out.println("当前随机文件名未重复，可用！");
                            break;
                        }

                    }


                    //File初始化参数(存放位置，文件名称)
                    File appFile = new File(appRootDir, RandomPrefix+"."+suffix);
                    //保存到指定位置 指定名称
                    file.transferTo(appFile);
                    String FileMD5 = Md5CaculateUtil.getMD5(appFile);
                    System.out.println("FileMD5:"+FileMD5);
                }
            }
        }

        //结束时间
        long endTime = System.currentTimeMillis();
        System.out.println("上传时间：" + String.valueOf(endTime - startTime) + "ms");
        res = new JsonResult();
        res.setCode(1);
        res.setMsg("上传时间：" + String.valueOf(endTime - startTime) + "ms");
        res.setData("");
        System.out.println(res.toString());
        return JSON.toJSONString(res);

    }



}
